package yxy.game.pm2.command.wuchao;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.WuchaoMessage;
import yxy.game.pm2.module.shop.Goods;
import yxy.game.pm2.module.shop.WuchaoShopModule;
import yxy.game.pm2.module.shop.handle.WuchaoShopHandle;
import yxy.game.pm2.module.wuchao.WuchaoModule;
import yxy.game.pm2.module.wuchao.event.WuchaoEvent;
import yxy.game.pm2.module.wuchao.event.WuchaoEvent.EventType;
import yxy.game.pm2.module.wuchao.event.WuchaoEventNewGoods;

import java.util.List;

/** 乌巢 乌巢事件新商品 */
@MessageType(proto = Command.WuchaoEventGoodsAdd, classtype = WuchaoMessage.WuchaoEventGoodsAddRequest.class)
public class CMD_WuchaoEventGoodsAdd extends Command<WuchaoMessage.WuchaoEventGoodsAddRequest> {

	@Override
	public void execute(MessageSource messageSource, WuchaoMessage.WuchaoEventGoodsAddRequest request) {
		String playerCode = messageSource.getTag();
		String eventCode = request.getCode();

		WuchaoMessage.WuchaoEventGoodsAddResponse.Builder response = WuchaoMessage.WuchaoEventGoodsAddResponse.newBuilder();

		WuchaoModule wuchaoModule = WuchaoModule.get(playerCode);
		if (wuchaoModule.getStage() <= 0) {
			send(messageSource, response, Result.WuchaoNotStart);// 没有开始挑战
			return;
		}
		try {
			if (wuchaoModule.tryLock()) {
				WuchaoEvent event = wuchaoModule.getEvents().get(eventCode);

				if (event == null || event.isOver()) {
					send(messageSource, response, Result.WuchaoEventOver);// 事件不可用
					return;
				}
				if (!(event.getEventType().equals(EventType.NewGoods))) {
					send(messageSource, response, Result.ParamError);// 事件不可用
					return;
				}

				List<Integer> goodsList = ((WuchaoEventNewGoods) event).getGoods();

				WuchaoShopHandle shopHandle = new WuchaoShopHandle();
				WuchaoShopModule shopModule = shopHandle.getModule(playerCode);
				for (Integer id : goodsList) {
					for (Goods goods : shopModule.getGoods()) {
						if (goods.getId() == id) {
							response.addGoods(shopHandle.packGoods(goods));
							break;
						}
					}
				}
				response.setCode(event.getCode());

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			wuchaoModule.unlock();
		}
	}

	private void send(MessageSource messageSource, WuchaoMessage.WuchaoEventGoodsAddResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}